package com.zhongxi.guoyuan.adapter.beautifulStoreOrder;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.navisdk.adapter.BNRoutePlanNode;
import com.baidu.navisdk.adapter.BaiduNaviManager;
import com.bumptech.glide.Glide;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.entity.beautifulOrder.BeautifulStoreOrderData;
import com.zhongxi.guoyuan.fragment.beautifulStoreOrder.StoreOrderHasNoApplyFragment;
import com.zhongxi.guoyuan.utils.ToastUtil;
import com.zhongxi.guoyuan.utils.UiUtils;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.view.MapNaviActivity;
import com.zhongxi.guoyuan.view.beautifulStore.OrderActivity;
import com.zhongxi.guoyuan.view.personalCenter.BeautifulStoreOrderActivity;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/11/21.
 */

public class StoreOrderHasNoApplyAdapter extends BaseAdapter {

    private StoreOrderHasNoApplyFragment fragment;
    private Handler handler;
    private Context context;
    private List<BeautifulStoreOrderData> list;
    private LayoutInflater mLayoutInflater;

    private JSONObject shopInfo;
    private int mExpandedMenuPos = -1;
    private String longitude;
    private String dimensions;
    private String mphone;
    private ProgressDialog dialog;
    private final static String authComArr[] = {Manifest.permission.READ_PHONE_STATE};
    private int authComRequestCode = 2;
    private boolean hasRequestComAuth = false;

    private DialogInterface.OnKeyListener keyListener = new DialogInterface.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
            if (i == KeyEvent.KEYCODE_BACK && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
            return false;
        }
    };
    private JSONObject shopidjson;

    public StoreOrderHasNoApplyAdapter(Context context, List<BeautifulStoreOrderData> data, Handler handler, StoreOrderHasNoApplyFragment fragment) {
        this.context = context;
        this.mLayoutInflater = LayoutInflater.from(context);
        this.list = data;
        this.handler = handler;
        this.fragment=fragment;
    }

    public int getmExpandedMenuPos() {
        return mExpandedMenuPos;
    }

    public void setmExpandedMenuPos(int mExpandedMenuPos) {
        this.mExpandedMenuPos = mExpandedMenuPos;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        try {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = mLayoutInflater.inflate(R.layout.item_beautiful_store_order, parent, false);
                holder.beautyProjectImage = (ImageView) convertView.findViewById(R.id.beauty_project_image);
                holder.beautyProjectTime = (TextView) convertView.findViewById(R.id.beauty_project_time);

                holder.beautyProjectName = (TextView) convertView.findViewById(R.id.beauty_project_name);
                holder.beautyProjectPayTime = (TextView) convertView.findViewById(R.id.beauty_project_payTime);
                holder.beautyProjectHongdou = (TextView) convertView.findViewById(R.id.beauty_project_hongdou);
                holder.beautyProjectMoney = (TextView) convertView.findViewById(R.id.beauty_project_money);
                holder.beautyProjectMeidou = (TextView) convertView.findViewById(R.id.beauty_project_meidou);
                holder.beautyProjectDetail = (TextView) convertView.findViewById(R.id.beauty_project_detail);
                holder.tvOper = (TextView) convertView.findViewById(R.id.tvOper);
                holder.tvComplain = (TextView) convertView.findViewById(R.id.tvComplain);
                holder.beautyProjectOrderNum = (TextView) convertView.findViewById(R.id.beauty_project_orderNum);
                holder.beautyProjectShopName = (TextView) convertView.findViewById(R.id.beauty_project_shopName);

                holder.beautyProjectCall = (TextView) convertView.findViewById(R.id.beauty_project_call);
                holder.beautyProjectShopPhone = (TextView) convertView.findViewById(R.id.beauty_project_shopPhone);
                holder.beautyProjectNavigation = (TextView) convertView.findViewById(R.id.beauty_project_navigation);
                holder.beautyProjectShopAddress = (TextView) convertView.findViewById(R.id.beauty_project_shopAddress);
                holder.beautyprojectWaitDeal = (TextView) convertView.findViewById(R.id.beauty_project_waitDeal);
                holder.relaMyInfo = (RelativeLayout) convertView.findViewById(R.id.relaMyInfo);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            final BeautifulStoreOrderData itemData = list.get(position);
            holder.beautyprojectWaitDeal.setVisibility(View.GONE);

            holder.tvOper.setVisibility(View.VISIBLE);
            holder.tvOper.setText("去支付");
            holder.tvOper.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (DataUtil.moreThanOther(MyApplication.getInstance().getInnerCurrency(), itemData.getShouldinnerprice())) {
                        Intent intent = new Intent(context, OrderActivity.class);
                        intent.putExtra("orderid", itemData.getId());
                        intent.putExtra("viewnum", itemData.getViewnum());
                        context.startActivity(intent);
                    } else {
                        Message message = Message.obtain();
                        message.what = 0;
                        message.obj = position;
                        handler.sendMessage(message);
                    }
                }
            });

            holder.tvComplain.setVisibility(View.VISIBLE);
            holder.tvComplain.setText(" 删  除 ");

            holder.tvComplain.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                  AlertDialog dialog=new AlertDialog.Builder(context).setTitle("您确定要删除该项目吗？")
                            .setPositiveButton("删除", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Message message = Message.obtain();
                                    message.what = 1;
                                    message.obj = position;
                                    handler.sendMessage(message);
                                    dialog.dismiss();
                                }
                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).show();
                    dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(context.getResources().getColor(R.color.bg_yield));
                    dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(context.getResources().getColor(R.color.bg_yield));

                }
            });
            //服务信息
            if (itemData != null) {
                if (null != itemData.getId() && !"".equals(itemData.getId())) {
                    holder.beautyProjectOrderNum.setText(itemData.getId());
                } else {
                    holder.beautyProjectOrderNum.setText("");
                }
                if (null != itemData.getItemname() && !"".equals(itemData.getItemname())) {
                    holder.beautyProjectName.setText(itemData.getItemname());
                } else {
                    holder.beautyProjectName.setText("");
                }

                if (null != itemData.getShouldinnerprice() && !"".equals(itemData.getShouldinnerprice())) {
                    holder.beautyProjectMeidou.setText(itemData.getShouldinnerprice() + "美豆");
                } else {
                    holder.beautyProjectMeidou.setText("");
                }

                if (null != itemData.getShouldredbeanprice() && !"".equals(itemData.getShouldredbeanprice())) {
                    holder.beautyProjectHongdou.setText( itemData.getShouldredbeanprice() + "红豆");
                } else {
                    holder.beautyProjectHongdou.setText("");
                }
                if (null != itemData.getCtime() && !"".equals(itemData.getCtime())) {
                    holder.beautyProjectPayTime.setText("下单：" + itemData.getCtime());
                } else {
                    holder.beautyProjectPayTime.setText("");
                }
                if (null != itemData.getThumbnail() && !"".equals(itemData.getThumbnail())) {
                    Glide.with(context).load(Url.IMG_URL + itemData.getThumbnail()).placeholder(R.mipmap.iv_eg).into(holder.beautyProjectImage);
                }
                if (null != itemData.getServicetime() && !"".equals(itemData.getServicetime())) {
                    holder.beautyProjectTime.setText(itemData.getServicetime() + "分钟");
                } else {
                    holder.beautyProjectTime.setText("");
                }
            }

            //店铺信息
            shopidjson = shopInfo.optJSONObject(itemData.getShopid());
            if (null != shopidjson && !"".equals(shopidjson)) {
                String name = shopidjson.optString("name");
                if (name != null && !"".equals(name)) {
                    holder.beautyProjectShopName.setText(name);
                } else {
                    holder.beautyProjectShopName.setText("");
                }
                mphone = shopidjson.optString("tel");
                if (mphone != null && !"".equals(mphone)) {
                    holder.beautyProjectShopPhone.setText(mphone);
                } else {
                    holder.beautyProjectShopPhone.setText("");
                }

                holder.beautyProjectCall.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String mphone1 = shopInfo.optJSONObject(list.get(position).getShopid()).optString("tel");

                        if (null != mphone1 && !"".equals(mphone1)) {
                            Intent intent = new Intent(Intent.ACTION_DIAL);
                            Uri data = Uri.parse("tel:" + mphone1);
                            intent.setData(data);
                            context.startActivity(intent);
                        } else {
                            Toast.makeText(context, "暂不可联系", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

                String address = shopidjson.optString("address");
                if (address != null && !"".equals(address)) {
                    holder.beautyProjectShopAddress.setText(address);
                } else {
                    holder.beautyProjectShopAddress.setText("");
                }
                //经 纬度

            } else {
                if (position != mExpandedMenuPos) {
                    Toast.makeText(context, "店铺已关闭", Toast.LENGTH_SHORT).show();
                    holder.beautyProjectShopName.setText("");
                    holder.beautyProjectShopPhone.setText("");
                    holder.beautyProjectShopAddress.setText("");
                }
            }


            holder.beautyProjectNavigation.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {


                    longitude = shopInfo.optJSONObject(list.get(position).getShopid()).optString("longitude");
                    dimensions = shopInfo.optJSONObject(list.get(position).getShopid()).optString("dimensions");

                    if (longitude != null && dimensions != null) {
                        if (dialog == null) {
                            dialog = new ProgressDialog(context);
                        }
                        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);  //样式为圆形
                        dialog.setCancelable(false);
                        dialog.setOnKeyListener(keyListener);
                        dialog.setMessage("正在获取数据,请稍后...");
                        dialog.show();

                        Log.d("flag", "onClick: "+position);
                        if (BaiduNaviManager.isNaviInited()) {
                            routeplanToNavi(BNRoutePlanNode.CoordinateType.BD09LL);
                        } else {
                            if (dialog != null && dialog.isShowing()) {
                                dialog.dismiss();
                            }
                        }
                    }else {
                        ToastUtil.show(UiUtils.getContext().getString(R.string.loseDataOfBaiduNavi));
                    }
                }


            });


            holder.beautyProjectDetail.setText(position == mExpandedMenuPos ? "收起" : "详情");

            holder.relaMyInfo.setVisibility(position == mExpandedMenuPos ? View.VISIBLE : View.GONE);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return convertView;
    }
    private boolean hasCompletePhoneAuth() {
        PackageManager pm = context.getPackageManager();
        for (String auth : authComArr) {
            if (pm.checkPermission(auth, context.getPackageName()) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }
    private void routeplanToNavi(BNRoutePlanNode.CoordinateType coType) {
        // 权限申请
        if (android.os.Build.VERSION.SDK_INT >= 23) {
            // 保证导航功能完备
            if (!hasCompletePhoneAuth()) {
                if (!hasRequestComAuth) {
                    hasRequestComAuth = true;
                    fragment.requestPermissions(authComArr, authComRequestCode);
                    return;
                }
            }

        }
        BNRoutePlanNode sNode = null;
        BNRoutePlanNode eNode = null;
        switch (coType) {
            case BD09LL: {
                sNode = new BNRoutePlanNode(Double.parseDouble(MyApplication.getInstance().getLongitude()), Double.parseDouble(MyApplication.getInstance().getLatitude()), "出发地", null, coType);
                eNode = new BNRoutePlanNode(Double.parseDouble(longitude), Double.parseDouble(dimensions), "美容院", null, coType);
                Log.d("flag", "routeplanToNavi: "+longitude+dimensions);
                break;
            }
            default:
        }
        if (sNode != null && eNode != null) {
            List<BNRoutePlanNode> list = new ArrayList<BNRoutePlanNode>();
            list.add(sNode);
            list.add(eNode);
            BaiduNaviManager.getInstance().launchNavigator((Activity) context, list, 1, true, new DemoRoutePlanListener(sNode));
        }
    }

    public void setShopInfo(JSONObject shopInfo) {
        this.shopInfo = shopInfo;
    }

    public class DemoRoutePlanListener implements BaiduNaviManager.RoutePlanListener {

        private BNRoutePlanNode mBNRoutePlanNode = null;

        public DemoRoutePlanListener(BNRoutePlanNode node) {
            mBNRoutePlanNode = node;
        }

        @Override
        public void onJumpToNavigator() {
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }
            /*
             * 设置途径点以及resetEndNode会回调该接口
			 */

            for (Activity ac : BeautifulStoreOrderActivity.activityList) {

                if (ac.getClass().getName().endsWith("MapNaviActivity")) {

                    return;
                }
            }
            Intent intent = new Intent(context, MapNaviActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(BeautifulStoreOrderActivity.ROUTE_PLAN_NODE, (BNRoutePlanNode) mBNRoutePlanNode);
            intent.putExtras(bundle);
            intent.putExtra("type", "1");
            context.startActivity(intent);

        }

        @Override
        public void onRoutePlanFailed() {
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }
            Toast.makeText(context, "导航失败", Toast.LENGTH_SHORT).show();
        }
    }

    class ViewHolder {
        private ImageView beautyProjectImage;
        private TextView beautyProjectTime, beautyProjectName, beautyProjectPayTime, beautyProjectHongdou, beautyProjectMoney, beautyProjectMeidou, beautyProjectDetail;
        private TextView tvOper, tvComplain, beautyProjectOrderNum, beautyProjectShopName, beautyProjectCall, beautyProjectShopPhone, beautyProjectNavigation, beautyProjectShopAddress, beautyprojectWaitDeal;
        private RelativeLayout relaMyInfo;
    }

}
